using System.Windows.Forms;
using TeachingManagementSystem.BLL;
using TeachingManagementSystem.Models;

namespace TeachingManagementSystem.Forms.UserManagement
{
    public partial class UserListForm : Form
    {
        private UserBLL _userBLL;

        public UserListForm()
        {
            InitializeComponent();
            _userBLL = new UserBLL();
            
            // 添加DataBindingComplete事件，确保数据绑定完成后格式化
            dataGridView1.DataBindingComplete += (sender, e) =>
            {
                FormatDataGridView();
            };
            
            // 设置为合适的大小
            this.WindowState = FormWindowState.Normal;
            this.Size = new System.Drawing.Size(900, 600);
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.StartPosition = FormStartPosition.CenterScreen;
            
            // 加载用户数据
            LoadUserData();
        }

        private void LoadUserData()
        {
            try
            {
                // 确保BLL实例不为null
                if (_userBLL == null)
                {
                    _userBLL = new UserBLL();
                }
                
                // 获取用户数据
                var users = _userBLL.GetAllUsers();
                
                // 清除之前的数据绑定
                dataGridView1.DataSource = null;
                
                // 重新设置数据源
                dataGridView1.DataSource = users;
                
                // 确保数据加载完成后再设置格式
                dataGridView1.Refresh();
                FormatDataGridView();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载用户数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FormatDataGridView()
        {
            if (dataGridView1 != null && dataGridView1.DataSource != null)
            {
                // 首先确保RoleText列存在且可见
                if (!dataGridView1.Columns.Contains("RoleText"))
                {
                    DataGridViewTextBoxColumn roleTextColumn = new DataGridViewTextBoxColumn();
                    roleTextColumn.Name = "RoleText";
                    roleTextColumn.HeaderText = "角色";
                    roleTextColumn.Width = 100;
                    dataGridView1.Columns.Add(roleTextColumn);
                }
                
                // 隐藏原始Role列
                if (dataGridView1.Columns["Role"] != null)
                {
                    dataGridView1.Columns["Role"].Visible = false;
                }
                
                // 隐藏不需要的列
                if (dataGridView1.Columns["Password"] != null)
                    dataGridView1.Columns["Password"].Visible = false;
                if (dataGridView1.Columns["CreatedDate"] != null)
                    dataGridView1.Columns["CreatedDate"].Visible = false;
                
                // 设置列标题
                if (dataGridView1.Columns["UserID"] != null)
                    dataGridView1.Columns["UserID"].HeaderText = "用户ID";
                if (dataGridView1.Columns["Username"] != null)
                    dataGridView1.Columns["Username"].HeaderText = "用户名";
                if (dataGridView1.Columns["FullName"] != null)
                    dataGridView1.Columns["FullName"].HeaderText = "姓名";
                if (dataGridView1.Columns["Email"] != null)
                    dataGridView1.Columns["Email"].HeaderText = "邮箱";
                if (dataGridView1.Columns["Phone"] != null)
                    dataGridView1.Columns["Phone"].HeaderText = "电话";
                if (dataGridView1.Columns["IsActive"] != null)
                    dataGridView1.Columns["IsActive"].HeaderText = "是否激活";
                
                // 填充角色文本
                if (dataGridView1.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        if (!row.IsNewRow && row.Cells["RoleText"] != null)
                        {
                            // 直接从数据源获取用户对象
                            if (row.DataBoundItem is User user && user != null)
                            {
                                // 使用用户对象的Role属性进行转换
                                string roleName = GetRoleDisplayName(user.Role.ToString());
                                row.Cells["RoleText"].Value = roleName;
                            }
                            else
                            {
                                row.Cells["RoleText"].Value = "未知角色";
                            }
                        }
                    }
                }
                
                // 设置列宽
                try
                {
                    dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                }
                catch (NullReferenceException)
                {
                    // 忽略可能的空引用异常
                }
            }
        }

        private void InitializeComponent()
        {
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.btnAdd = new System.Windows.Forms.Button();
            this.btnEdit = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.btnRefresh = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.comboBoxRoleFilter = new System.Windows.Forms.ComboBox();
            this.label2 = new System.Windows.Forms.Label();
            this.txtSearch = new System.Windows.Forms.TextBox();
            this.btnSearch = new System.Windows.Forms.Button();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.tableLayoutPanel1.SuspendLayout();
            this.tableLayoutPanel2.SuspendLayout();
            this.SuspendLayout();
            // 
            // tableLayoutPanel1
            // 
            this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            this.tableLayoutPanel1.ColumnCount = 5;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 190F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 190F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 75F));
            this.tableLayoutPanel1.Location = new System.Drawing.Point(20, 20);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 1;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(750, 60);
            this.tableLayoutPanel1.TabIndex = 10;
            // 
            // tableLayoutPanel2
            // 
            this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.tableLayoutPanel2.ColumnCount = 4;
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel2.Location = new System.Drawing.Point(20, 490);
            this.tableLayoutPanel2.Name = "tableLayoutPanel2";
            this.tableLayoutPanel2.RowCount = 1;
            this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel2.Size = new System.Drawing.Size(750, 30);
            this.tableLayoutPanel2.TabIndex = 11;
            // 
            // dataGridView1
            // 
            this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(20, 100);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.RowHeadersWidth = 51;
            this.dataGridView1.RowTemplate.Height = 27;
            this.dataGridView1.Size = new System.Drawing.Size(750, 380);
            this.dataGridView1.TabIndex = 0;
            this.dataGridView1.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellDoubleClick);
            // 
            // label1
            // 
            this.label1.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(3, 22);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(74, 15);
            this.label1.TabIndex = 5;
            this.label1.Text = "角色筛选:";
            // 
            // comboBoxRoleFilter
            // 
            this.comboBoxRoleFilter.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.comboBoxRoleFilter.FormattingEnabled = true;
            this.comboBoxRoleFilter.Items.AddRange(new object[] {
            "全部",
            "管理员",
            "教师",
            "学生",
            "行政人员"});
            this.comboBoxRoleFilter.Location = new System.Drawing.Point(83, 19);
            this.comboBoxRoleFilter.Name = "comboBoxRoleFilter";
            this.comboBoxRoleFilter.Size = new System.Drawing.Size(184, 23);
            this.comboBoxRoleFilter.TabIndex = 6;
            this.comboBoxRoleFilter.Text = "全部";
            this.comboBoxRoleFilter.SelectedIndexChanged += new System.EventHandler(this.comboBoxRoleFilter_SelectedIndexChanged);
            // 
            // label2
            // 
            this.label2.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(269, 22);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(74, 15);
            this.label2.TabIndex = 7;
            this.label2.Text = "搜索:";
            // 
            // txtSearch
            // 
            this.txtSearch.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.txtSearch.Location = new System.Drawing.Point(349, 19);
            this.txtSearch.Name = "txtSearch";
            this.txtSearch.Size = new System.Drawing.Size(184, 25);
            this.txtSearch.TabIndex = 8;
            // 
            // btnSearch
            // 
            this.btnSearch.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.btnSearch.Location = new System.Drawing.Point(539, 19);
            this.btnSearch.Name = "btnSearch";
            this.btnSearch.Size = new System.Drawing.Size(60, 25);
            this.btnSearch.TabIndex = 9;
            this.btnSearch.Text = "查找";
            this.btnSearch.UseVisualStyleBackColor = true;
            this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            // 
            // btnAdd
            // 
            this.btnAdd.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btnAdd.Location = new System.Drawing.Point(3, 3);
            this.btnAdd.Name = "btnAdd";
            this.btnAdd.Size = new System.Drawing.Size(74, 24);
            this.btnAdd.TabIndex = 1;
            this.btnAdd.Text = "添加";
            this.btnAdd.UseVisualStyleBackColor = true;
            this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
            // 
            // btnEdit
            // 
            this.btnEdit.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btnEdit.Location = new System.Drawing.Point(83, 3);
            this.btnEdit.Name = "btnEdit";
            this.btnEdit.Size = new System.Drawing.Size(74, 24);
            this.btnEdit.TabIndex = 2;
            this.btnEdit.Text = "编辑";
            this.btnEdit.UseVisualStyleBackColor = true;
            this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
            // 
            // btnDelete
            // 
            this.btnDelete.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btnDelete.Location = new System.Drawing.Point(163, 3);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(74, 24);
            this.btnDelete.TabIndex = 3;
            this.btnDelete.Text = "删除";
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            // 
            // btnRefresh
            // 
            this.btnRefresh.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.btnRefresh.Location = new System.Drawing.Point(672, 3);
            this.btnRefresh.Name = "btnRefresh";
            this.btnRefresh.Size = new System.Drawing.Size(75, 24);
            this.btnRefresh.TabIndex = 4;
            this.btnRefresh.Text = "刷新";
            this.btnRefresh.UseVisualStyleBackColor = true;
            this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
            // 
            // UserListForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(792, 543);
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.MaximizeBox = true;
            this.MinimizeBox = true;
            this.Controls.Add(this.tableLayoutPanel2);
            this.Controls.Add(this.tableLayoutPanel1);
            this.Controls.Add(this.dataGridView1);
            this.Name = "UserListForm";
            this.Text = "用户列表";
            this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
            this.tableLayoutPanel1.Controls.Add(this.comboBoxRoleFilter, 1, 0);
            this.tableLayoutPanel1.Controls.Add(this.label2, 2, 0);
            this.tableLayoutPanel1.Controls.Add(this.txtSearch, 3, 0);
            this.tableLayoutPanel1.Controls.Add(this.btnSearch, 4, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnAdd, 0, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnEdit, 1, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnDelete, 2, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnRefresh, 3, 0);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.tableLayoutPanel2.ResumeLayout(false);
            this.ResumeLayout(false);
        }
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;

        private void btnAdd_Click(object? sender, EventArgs e)
        {
            User newUser = new User();
            if (newUser != null) {
                UserEditForm userEditForm = new UserEditForm(newUser);
                if (userEditForm.ShowDialog() == DialogResult.OK) {
                    // 重新加载数据
                    LoadUserData();
                }
            }
        }

        private void btnEdit_Click(object? sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                object? boundItem = dataGridView1.SelectedRows[0].DataBoundItem;
                if (boundItem is User selectedUser)
                {
                    if (selectedUser != null) {
                    UserEditForm userEditForm = new UserEditForm(selectedUser);
                    if (userEditForm.ShowDialog() == DialogResult.OK) {
                        // 重新加载数据
                        LoadUserData();
                    }
                }
                }
                else
                {
                    MessageBox.Show("无法获取用户信息", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("请选择要编辑的用户", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnDelete_Click(object? sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                object? boundItem = dataGridView1.SelectedRows[0].DataBoundItem;
                if (boundItem is User selectedUser)
                {
                    if (MessageBox.Show($"确定要删除用户 {selectedUser.FullName} 吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        _userBLL.DeleteUser(selectedUser.UserID);
                        MessageBox.Show("用户已删除", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 重新加载数据
                        LoadUserData();
                    }
                }
                else
                {
                    MessageBox.Show("无法获取用户信息", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("请选择要删除的用户", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnRefresh_Click(object? sender, EventArgs e)
        {
            LoadUserData();
            comboBoxRoleFilter.Text = "全部";
            txtSearch.Text = "";
        }

        private void dataGridView1_CellDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                object? boundItem = dataGridView1.Rows[e.RowIndex].DataBoundItem;
                if (boundItem is User selectedUser)
                {
                    if (selectedUser != null) {
                    UserEditForm userEditForm = new UserEditForm(selectedUser);
                    if (userEditForm.ShowDialog() == DialogResult.OK) {
                        // 重新加载数据
                        LoadUserData();
                    }
                }
                }
            }
        }

        private void comboBoxRoleFilter_SelectedIndexChanged(object? sender, EventArgs e)
        {
            string selectedRole = comboBoxRoleFilter.SelectedItem?.ToString() ?? "全部";
            if (selectedRole == "全部")
            {
                LoadUserData();
            }
            else
            {
                UserRole role = UserRole.Student; // 默认值
                switch (selectedRole)
                {
                    case "管理员":
                        role = UserRole.Administrator;
                        break;
                    case "教师":
                        role = UserRole.Teacher;
                        break;
                    case "学生":
                        role = UserRole.Student;
                        break;
                    case "行政人员":
                        role = UserRole.Staff;
                        break;
                }
                var filteredUsers = _userBLL.GetUsersByRole(role);
                dataGridView1.DataSource = filteredUsers;
                FormatDataGridView();
            }
        }

        private void btnSearch_Click(object? sender, EventArgs e)
        {
            string searchText = txtSearch.Text.Trim().ToLower();
            if (!string.IsNullOrEmpty(searchText))
            {
                var allUsers = _userBLL.GetAllUsers();
                var filteredUsers = allUsers.Where(u => 
                    (!string.IsNullOrEmpty(u.Username) && u.Username.ToLower().Contains(searchText)) || 
                    (!string.IsNullOrEmpty(u.FullName) && u.FullName.ToLower().Contains(searchText)) ||
                    (!string.IsNullOrEmpty(u.Email) && u.Email.ToLower().Contains(searchText)) ||
                    (!string.IsNullOrEmpty(u.Phone) && u.Phone.Contains(searchText))).ToList();
                dataGridView1.DataSource = filteredUsers;
                FormatDataGridView();
            }
            else
            {
                LoadUserData();
            }
        }

        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.Button btnAdd;
        private System.Windows.Forms.Button btnEdit;
        private System.Windows.Forms.Button btnDelete;
        private System.Windows.Forms.Button btnRefresh;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.ComboBox comboBoxRoleFilter;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtSearch;
        private System.Windows.Forms.Button btnSearch;
        private string GetRoleDisplayName(string roleEnumName)
        {
            if (string.IsNullOrEmpty(roleEnumName))
                return "未知角色";
                
            switch (roleEnumName)
            {
                case "Administrator":
                    return "管理员";
                case "Teacher":
                    return "教师";
                case "Student":
                    return "学生";
                case "Staff":
                    return "行政人员";
                default:
                    return "未知角色";
            }
        }
    }
}